<template>
  <div class="comments-management">
    <!-- 页面标题和操作栏 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
      <div>
        <h2 class="page-title mb-1">评论管理</h2>
        <p class="text-muted mb-0">管理系统所有评论，支持查看、删除等操作</p>
      </div>
    </div>

    <!-- 搜索和筛选栏 -->
    <div class="card mb-4">
      <div class="card-body">
        <div class="row g-3 align-items-end">
          <div class="col-md-3">
            <label class="form-label">关键词搜索</label>
            <div class="input-group">
              <span class="input-group-text">
                <i class="bi bi-search"></i>
              </span>
              <input 
                type="text" 
                class="form-control" 
                placeholder="搜索评论内容..."
                v-model="searchQuery"
                @input="handleSearch"
              >
            </div>
          </div>
          <div class="col-md-3">
            <label class="form-label">所属帖子</label>
            <select class="form-select" v-model="filters.postId" @change="filterComments">
              <option value="">全部帖子</option>
              <option v-for="post in posts" :key="post.id" :value="post.id">
                {{ post.title }}
              </option>
            </select>
          </div>
          <div class="col-md-3">
            <label class="form-label">评论状态</label>
            <select class="form-select" v-model="filters.status" @change="filterComments">
              <option value="">全部状态</option>
              <option value="normal">正常</option>
              <option value="hidden">隐藏</option>
            </select>
          </div>
          <div class="col-md-3">
            <button class="btn btn-outline-secondary w-100" @click="resetFilters">
              <i class="bi bi-arrow-clockwise me-2"></i>重置筛选
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 评论列表 -->
    <div class="card">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="card-title mb-0">评论列表</h5>
        <div class="d-flex align-items-center gap-2">
          <span class="text-muted small">共 {{ filteredComments.length }} 条评论</span>
        </div>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-hover align-middle mb-0">
            <thead class="table-light">
              <tr>
                <th width="50">
                  <div class="d-flex justify-content-center align-items-center">
                    <span 
                      class="fw-bold text-primary" 
                      style="cursor: pointer; font-size: 1rem;" 
                      @click="toggleSelectAll"
                    >
                      {{ selectAll ? '取消全选' : '全选' }}
                    </span>
                  </div>
                </th>
                <th width="100">用户</th>
                <th>评论内容</th>
                <th width="150">所属帖子</th>
                <th width="80">点赞数</th>
                <th width="80">状态</th>
                <th width="120">评论时间</th>
                <th width="120">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="comment in paginatedComments" :key="comment.id" :class="{ 'table-active': selectedComments.includes(comment.id) }">
                <td>
                  <div class="form-check">
                    <input 
                      type="checkbox" 
                      class="form-check-input form-check-input-lg" 
                      :value="comment.id"
                      v-model="selectedComments"
                      :id="'comment-check-' + comment.id"
                    >
                    <label class="form-check-label" :for="'comment-check-' + comment.id"></label>
                  </div>
                </td>
                <td>
                  <div class="d-flex flex-column">
                    <strong>{{ comment.userNickname || comment.username || '未知用户' }}</strong>
                    <small class="text-muted">ID: {{ comment.userId }}</small>
                  </div>
                </td>
                <td>
                  <div class="d-flex flex-column">
                    <span class="text-truncate" style="max-width: 300px;">{{ comment.content }}</span>
                    <small v-if="comment.parentId !== 0" class="text-muted">
                      回复 #{{ comment.parentId }}
                    </small>
                  </div>
                </td>
                <td>
                  <div class="d-flex flex-column">
                    <strong class="text-primary text-truncate" style="max-width: 150px;">
                      {{ getPostTitle(comment.postId) }}
                    </strong>
                    <small class="text-muted">ID: {{ comment.postId }}</small>
                  </div>
                </td>
                <td>{{ comment.likeCount || 0 }}</td>
                <td>
                  <span class="badge" :class="comment.status === 'normal' ? 'bg-success' : 'bg-secondary'">
                    {{ comment.status === 'normal' ? '正常' : '隐藏' }}
                  </span>
                </td>
                <td>
                  <div class="d-flex flex-column">
                    <small class="text-muted">{{ formatDate(comment.createdAt) }}</small>
                  </div>
                </td>
                <td>
                  <div class="btn-group btn-group-sm">
                    <button 
                      class="btn btn-outline-primary"
                      @click="viewPost(comment.postId)"
                      title="查看"
                    >
                      <i class="bi bi-eye"></i>
                    </button>
                    <button 
                      class="btn btn-outline-danger"
                      @click="deleteComment(comment)"
                      title="删除"
                    >
                      <i class="bi bi-trash"></i>
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 空状态 -->
        <div v-if="filteredComments.length === 0" class="text-center py-5">
          <i class="bi bi-chat-square-text display-1 text-muted"></i>
          <p class="text-muted mt-3">暂无评论数据</p>
        </div>
      </div>

      <!-- 分页 -->
      <div class="card-footer d-flex justify-content-between align-items-center">
        <div class="text-muted small">
          显示第 {{ startIndex + 1 }} 到 {{ endIndex }} 条，共 {{ filteredComments.length }} 条
        </div>
        <nav>
          <ul class="pagination pagination-sm mb-0">
            <li class="page-item" :class="{ disabled: currentPage === 1 }">
              <button class="page-link" @click="prevPage">
                <i class="bi bi-chevron-left"></i>
              </button>
            </li>
            <li 
              v-for="page in totalPages" 
              :key="page"
              class="page-item"
              :class="{ active: page === currentPage }"
            >
              <button class="page-link" @click="goToPage(page)">{{ page }}</button>
            </li>
            <li class="page-item" :class="{ disabled: currentPage === totalPages }">
              <button class="page-link" @click="nextPage">
                <i class="bi bi-chevron-right"></i>
              </button>
            </li>
          </ul>
        </nav>
      </div>
    </div>

    <!-- 批量操作栏 -->
    <div v-if="selectedComments.length > 0" class="batch-actions fixed-bottom bg-primary text-white p-4 shadow-lg">
      <div class="container-fluid">
        <div class="row align-items-center">
          <div class="col">
            <span class="h5 mb-0 text-white">已选择 <strong>{{ selectedComments.length }}</strong> 条评论</span>
          </div>
          <div class="col-auto">
            <button class="btn btn-danger btn-lg" @click="batchDeleteComments">
              <i class="bi bi-trash me-2"></i>批量删除
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllCommentsService, deleteAdminCommentService, batchDeleteAdminCommentsService } from '@/api/comments.js'
import { getPostAllService } from '@/api/post.js'
import { getUserInfoByIdService } from '@/api/user.js'

//导入路由
const router = useRouter()


// 响应式数据
const allComments = ref([])
const posts = ref([])
const users = ref(new Map()) // 缓存用户信息
const searchQuery = ref('')
const selectedComments = ref([])
const currentPage = ref(1)
const pageSize = ref(10)

// 筛选条件
const filters = ref({
  status: '',
  postId: ''
})

// 计算属性 - 全选状态
const selectAll = computed({
  get: () => filteredComments.value.length > 0 && selectedComments.value.length === filteredComments.value.length,
  set: (value) => {
    if (value) {
      selectedComments.value = filteredComments.value.map(comment => comment.id)
    } else {
      selectedComments.value = []
    }
  }
})

// 计算属性 - 筛选后的评论
const filteredComments = computed(() => {
  let result = [...allComments.value]
  
  // 关键词搜索
  if (searchQuery.value) {
    const keyword = searchQuery.value.toLowerCase()
    result = result.filter(comment => 
      comment.content.toLowerCase().includes(keyword)
    )
  }
  
  // 状态筛选
  if (filters.value.status) {
    result = result.filter(comment => comment.status === filters.value.status)
  }
  
  // 帖子筛选
  if (filters.value.postId) {
    result = result.filter(comment => comment.postId == filters.value.postId)
  }
  
  return result
})

// 计算属性 - 分页后的评论
const paginatedComments = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredComments.value.slice(start, end)
})

// 计算属性 - 总页数
const totalPages = computed(() => {
  return Math.ceil(filteredComments.value.length / pageSize.value) || 1
})

// 计算属性 - 起始索引
const startIndex = computed(() => {
  return (currentPage.value - 1) * pageSize.value
})

// 计算属性 - 结束索引
const endIndex = computed(() => {
  return Math.min(currentPage.value * pageSize.value, filteredComments.value.length)
})



// 方法
const loadComments = async () => {
  try {
    const response = await getAllCommentsService()
    if (response.code === 0) {
      allComments.value = response.data || []
      
      // 获取用户信息
      for (const comment of allComments.value) {
        if (!users.value.has(comment.userId)) {
          try {
            const userResponse = await getUserInfoByIdService(comment.userId)
            if (userResponse.code === 0) {
              users.value.set(comment.userId, userResponse.data)
              // 将用户名添加到评论对象中
              comment.username = userResponse.data.username
              comment.userNickname = userResponse.data.nickname
            }
          } catch (error) {
            console.error('获取用户信息失败:', error)
          }
        } else {
          const user = users.value.get(comment.userId)
          comment.username = user.username
          comment.userNickname = user.nickname
        }
      }
    } else {
      ElMessage.error('获取评论列表失败: ' + response.msg)
    }
  } catch (error) {
    ElMessage.error('获取评论列表失败: ' + error.message)
  }
}

// 获取所有帖子
const loadPosts = async () => {
  try {
    const response = await getPostAllService()
    if (response.code === 0) {
      posts.value = response.data || []
    } else {
      ElMessage.error('获取帖子列表失败: ' + response.msg)
    }
  } catch (error) {
    ElMessage.error('获取帖子列表失败: ' + error.message)
  }
}

const getPostTitle = (postId) => {
  if (!postId) return '未知帖子'
  const post = posts.value.find(p => p.id == postId)
  return post ? post.title : '未知帖子'
}

// 删除评论
const deleteComment = async (comment) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除评论 "${comment.content.substring(0, 20)}${comment.content.length > 20 ? '...' : ''}" 吗？此操作不可逆！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await deleteAdminCommentService(comment.id)
    if (response.code === 0) {
      await loadComments()
      ElMessage.success('评论删除成功')
    } else {
      ElMessage.error('删除评论失败: ' + response.msg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除评论失败: ' + error.message)
    }
  }
}

//批量删除评论
const batchDeleteComments = async () => {
  if (selectedComments.value.length === 0) {
    ElMessage.warning('请先选择评论')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedComments.value.length} 条评论吗？此操作不可逆！`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await batchDeleteAdminCommentsService(selectedComments.value)
    if (response.code === 0) {
      await loadComments()
      selectedComments.value = []
      ElMessage.success('评论批量删除成功')
    } else {
      ElMessage.error('批量删除评论失败: ' + response.msg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除评论失败: ' + error.message)
    }
  }
}

const toggleSelectAll = () => {
  selectAll.value = !selectAll.value
}

const handleSearch = () => {
  currentPage.value = 1
}

const filterComments = () => {
  currentPage.value = 1
}

const resetFilters = () => {
  searchQuery.value = ''
  filters.value.status = ''
  filters.value.postId = ''
  currentPage.value = 1
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const viewPost = (postId) => {
  // 跳转到帖子详情页面
  router.push(`/admin/posts/${postId}`)
//   window.open(`/admin/posts/${postId}`, '_blank')
}

// 分页方法
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
  }
}

const goToPage = (page) => {
  currentPage.value = page
}

// 生命周期
onMounted(() => {
  loadComments()
  loadPosts()
})
</script>

<style scoped>
.page-title {
  color: #2c3e50;
  font-weight: 600;
}

.table th {
  border-top: none;
  font-weight: 600;
  color: #6c757d;
  font-size: 0.875rem;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.table-hover > tbody > tr:hover > td {
  background-color: #e3f2fd !important;
}

.table > tbody > tr {
  transition: background-color 0.2s ease;
}

.form-check-input-lg {
  width: 1.5em;
  height: 1.5em;
  margin-top: 0;
  border: 2px solid #0d6efd;
  transition: all 0.2s ease;
}

.form-check-input-lg:checked {
  border: 3px solid #0d6efd;
  background-color: #0d6efd;
}

.form-check {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 0;
}

.form-check-label {
  cursor: pointer;
  user-select: none;
}

.batch-actions {
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  border-top: 3px solid #0d6efd !important;
  animation: slideInUp 0.3s ease-out;
}

@keyframes slideInUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .table-responsive {
    font-size: 0.875rem;
  }
  
  .btn-group-sm > .btn {
    padding: 0.25rem 0.5rem;
  }
}
</style>